package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.Map;

@Controller
@SessionAttributes("cart")
@RequestMapping("/cart")
public class CartController {

    @Autowired
    CatalogService catalogService;
    @Autowired
    CartService cartService;

    @GetMapping("/viewCart")
    public String viewCart( HttpSession session, Model model, Map<String,Object> map ) {
        Account account = (Account) session.getAttribute( "account" );
        if(account == null || !account.isAuthenticated()){
            return "account/signin";
        }

        Cart cart = cartService.getCartByUsername( account.getUsername() );
        session.setAttribute( "cart", cart );

        return "cart/cart";
    }

    @GetMapping("/addItemToCart")
    public String addItemToCart( HttpSession session, String workingItemId, Map<String, Object> map ) {
        Account account = (Account) session.getAttribute( "account" );
        if(account == null || !account.isAuthenticated()){
            return "account/signin";
        }

        cartService.addItemToCart( workingItemId, account.getUsername() );

        Cart cart = cartService.getCartByUsername( account.getUsername() );

//        model.addAttribute( "cart", cart );
        map.put("cart", cart);

        return "cart/cart";
    }

    @PostMapping("/updateCartQuantities")
    @ResponseBody
    public String updateCartQutantites( HttpSession session, @RequestBody Map<String, String> map ){

        int quantity, originalQuantity;
        Cart cart = ( Cart )session.getAttribute( "cart" );
        Account account = ( Account )session.getAttribute( "account" );

        Iterator<CartItem> cartItems = cart.getAllCartItems();
        boolean isSthRemoved = false;
        StringBuilder removedItemsString = new StringBuilder("");

        while (cartItems.hasNext()) {
            CartItem cartItem = cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            quantity = Integer.parseInt(map.get(itemId));
            originalQuantity = cart.getStockQuantityByItemId(itemId);
            cart.setCartQuantityByItemId(itemId, quantity);
            if (quantity < 1) {
                cartItems.remove();
                removedItemsString.append( "," ).append( cartItem.getItem().getItemId() );
                isSthRemoved = true;
            }
        }

        cartService.updateCartDBByCart( cart, account.getUsername() );
        session.setAttribute( "cart", cart );

        StringBuilder message = new StringBuilder("");

        if( !isSthRemoved ){
            message.append( "No Remove Action" );
        }else{
            message.append( "Remove Action/" ); /*Append a '/' in the end for js to call split('/')*/
            if(cart.getNumberOfItems() == 0){
                message.append( "Empty" );
            }
            message.append( removedItemsString );
        }
        return message.toString();
    }

    @GetMapping("/removeItemFromCart")
    @ResponseBody
    public String removeItemFromCart( HttpSession session, String workingItemId ) {

        Cart cart = (Cart) session.getAttribute( "cart" );
        Item item = cart.removeItemById( workingItemId );

        Account account = (Account)session.getAttribute( "account" );
        cartService.removeCartItem( workingItemId, account.getUsername() );

        if ( item == null ) {
            session.setAttribute( "message", "Attempted to remove null CartItem from Cart." );
//            request.getRequestDispatcher(ERROR).forward(request, response);
        } else {

            if ( cart.getNumberOfItems() == 0 ) {
                return "Cart Empty";
            }

        }
        return "Cart Not Empty";
    }

}
